package com.ziyueyuwen.xiniao.controller.manage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.suyeer.basic.util.HttpResUtil;
import com.ziyueyuwen.xiniao.base.BaseUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.bean.ZyUser;
import com.ziyueyuwen.xiniao.bean.homework.*;
import com.ziyueyuwen.xiniao.bean.vo.ZyUserVO;
import com.ziyueyuwen.xiniao.enums.QuestionTypeEnum;
import com.ziyueyuwen.xiniao.enums.RoleEnum;
import com.ziyueyuwen.xiniao.service.*;
import com.ziyueyuwen.xiniao.service.report.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.ziyueyuwen.xiniao.base.BaseUtil.checkParam;
import static com.ziyueyuwen.xiniao.util.ConstUtil.*;

/**
 * @author jun 2018/12/20.
 */
@Controller
@RequestMapping("/manage/homework")
public class ManageHomeworkController {
    @Autowired
    private SubjectService subjectService;

    @Autowired
    private SubjectQuestionService subjectQuestionService;

    @Autowired
    private HomeworkRecordService homeworkRecordService;

    @Autowired
    private WxMessageService wxMessageService;

    @Autowired
    private UserService userService;

    @Autowired
    ReportService reportService;

    @Autowired
    RoleService roleService;

    /**
     * 获取所有套题名称, 用于绑定课程数据
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping(value = "/list_all_subject.do", method = RequestMethod.POST)
    public void listAllSubject(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<ZySubjectDO>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取所有套题名称");
        try {
            List<ZySubjectDO> retList = subjectService.listAll();
            BaseUtil.saveSuccessMsgAndData(hrc, retList);
        } catch (Exception e) {
            BaseUtil.saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    /**
     * 获取套题下所有的题, 所有课节对应的题
     *
     * @param subjectId Integer
     * @param request   HttpServletRequest
     * @param response  HttpServletResponse
     */
    @RequestMapping(value = "/list_all_question_by_subject_id.do", method = RequestMethod.POST)
    public void listAllQuestionBySubjectId(@RequestParam(PARAM_SUBJECT_ID) Integer subjectId,
                                           HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<ZySubjectQuestionDO>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取套题下所有的题");
        try {
            // check.
            checkParam(PARAM_SUBJECT_ID, subjectId);
            // do.
            List<ZySubjectQuestionDO> retList = subjectQuestionService.listBySubjectId(subjectId);
            BaseUtil.saveSuccessMsgAndData(hrc, retList);
        } catch (Exception e) {
            BaseUtil.saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    /**
     * 获取课节对应的题
     *
     * @param id       Integer
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping(value = "/get_question.do", method = RequestMethod.POST)
    public void getQuestion(@RequestParam(PARAM_ID) Integer id,
                            HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<ZySubjectQuestionDO> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取课节对应的题");
        try {
            // check.
            checkParam(PARAM_ID, id);
            // do.
            ZySubjectQuestionDO ret = subjectQuestionService.getById(id);
            BaseUtil.saveSuccessMsgAndData(hrc, ret);
        } catch (Exception e) {
            BaseUtil.saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_student_homework_record.do", method = RequestMethod.POST)
    public void getStudentHomeworkRecord(@RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                                         HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生作业记录");
        try {
            // check.
            checkParam(PARAM_HOMEWORK_RECORD_ID, homeworkRecordId);
            // do.
            JSONObject retObj = new JSONObject();
            ZyHomeworkRecordDO zyHomeworkRecord = homeworkRecordService.getById(homeworkRecordId);
            if (zyHomeworkRecord == null) {
                throw new Exception("获取作业记录失败!");
            }
            ZySubjectQuestionDO zySubjectQuestion = subjectQuestionService.getById(zyHomeworkRecord.getSubjectQuestionId());
            retObj.put("subjectQuestionInfo", zySubjectQuestion);
            retObj.put("studentHomeworkRecord", zyHomeworkRecord);
            BaseUtil.saveSuccessMsgAndData(hrc, retObj);
        } catch (Exception e) {
            BaseUtil.saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/list_homework_record.do", method = RequestMethod.POST)
    public void listHomeworkRecord(@RequestParam(PARAM_PAGE_NUM) Integer pageNum,
                                   @RequestParam(PARAM_PAGE_SIZE) Integer pageSize,
                                   HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<JSONObject> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取学生作业记录列表");
        try {
            // check.
            checkParam(PARAM_PAGE_NUM, pageNum);
            checkParam(PARAM_PAGE_SIZE, pageSize);
            // do.
            String userId = hrc.getUserInfo().getUserAccount();
            Boolean ifHasRole = roleService.ifHasRole(userId, RoleEnum.ADMIN);
            if (ifHasRole) {
                userId = null;
            }
            JSONObject retObj = new JSONObject();
            Page page = PageHelper.startPage(pageNum, pageSize);
            List<HomeworkRecordNotMarkVO> retList = homeworkRecordService.listHomeworkRecordNotMark(userId);
            retObj.put(KEY_TOTAL, page.getTotal());
            retObj.put(KEY_INFO_LIST, retList);
            BaseUtil.saveSuccessMsgAndData(hrc, retObj);
        } catch (Exception e) {
            e.printStackTrace();
            BaseUtil.saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/mark_homework_record.do", method = RequestMethod.POST)
    public void markHomeworkRecord(@RequestParam(PARAM_HOMEWORK_RECORD_ID) Integer homeworkRecordId,
                                   @RequestParam(PARAM_MARK_DATA_INFO) String markDataInfo) throws Exception {
        HttpResContent<Boolean> hrc = new HttpResContent<>("评分");
        // check.
        checkParam(PARAM_HOMEWORK_RECORD_ID, homeworkRecordId);
        checkParam(PARAM_MARK_DATA_INFO, markDataInfo);
        // do.
        ZyUser zyUser = hrc.getUserInfo();
        HomeworkMarkData homeworkMarkData = JSON.parseObject(markDataInfo, HomeworkMarkData.class);
        ZyUserVO userVO = userService.getUserMessage(zyUser.getUserAccount());
        homeworkMarkData.setTeacherImg(userVO.getDingTalkHeadUrl());
        ZyHomeworkRecordDO zyHomeworkRecord = homeworkRecordService.getById(homeworkRecordId);
        if (zyHomeworkRecord == null) {
            throw new Exception("获取作业记录失败!");
        }
        List<AnswerData> answerInfoList = zyHomeworkRecord.getAnswerInfoList();
        HashMap<String, MarkData> questionMarkMap = homeworkMarkData.getQuestionMarkMap();
        for (String questionNum : questionMarkMap.keySet()) {
            AnswerData answerData;
            if (questionNum.contains("-")) {
                String[] arr = questionNum.trim().split("-");
                answerData = answerInfoList.get(Integer.valueOf(arr[0]) - 1).getGroupAnswerDataList().get(Integer.valueOf(arr[1]) - 1);
            } else {
                answerData = answerInfoList.get(Integer.valueOf(questionNum) - 1);
            }
            MarkData markData = questionMarkMap.get(questionNum);
            HashMap<String, Integer> scoreMap = markData.getMarkScoreMap();
            int totalScore = 0;
            for (Integer score : scoreMap.values()) {
                totalScore += score;
            }
            answerData.setCorrectScore(totalScore);
        }
        // 组合题计算整个题的得分
        for (AnswerData answerData : answerInfoList) {
            if (answerData.getQuestionType() == QuestionTypeEnum.GROUP) {
                int correct = 0;
                for (AnswerData a : answerData.getGroupAnswerDataList()) {
                    correct += a.getCorrectScore();
                }
                answerData.setCorrectScore(correct);
            }
        }
        if (!homeworkRecordService.markHomeworkRecord(zyHomeworkRecord.getId(), homeworkMarkData, zyHomeworkRecord.getAnswerInfoList())) {
            throw new Exception("保存数据失败!");
        }
        //修改课堂报告分数
        reportService.updateReportScore(zyHomeworkRecord.getStudentId(), zyHomeworkRecord.getLessonId());
        //发送配改消息
        wxMessageService.sendLessonHomeworkCorrect(zyHomeworkRecord.getStudentId(), hrc.getUserInfo().getUserName(), zyHomeworkRecord.getLessonId(), new Date());
        hrc.printLogAndResponse(true);
    }

    @RequestMapping(value = "/list_mould.do", method = RequestMethod.POST)
    public void listMould(@RequestParam(PARAM_COURSE_ID) Integer courseId,
                          @RequestParam(PARAM_LESSON_INDEX) Integer lessonIndex) throws Exception {
        HttpResContent<JSONArray> hrc = new HttpResContent<>("获取课堂互动模板列表");
        // check.
        checkParam(PARAM_COURSE_ID, courseId);
        checkParam(PARAM_LESSON_INDEX, lessonIndex);
        List<String> retList = subjectQuestionService.listMould(courseId, lessonIndex);
        JSONArray retArr = new JSONArray();
        for (String s : retList) {
            JSONObject obj = new JSONObject();
            obj.put("content", s);
            retArr.add(obj);
        }
        hrc.printLogAndResponse(retArr);
    }

    @RequestMapping(value = "/list_tag.do", method = RequestMethod.POST)
    public void listTag(@RequestParam(PARAM_COURSE_ID) Integer courseId,
                        @RequestParam(PARAM_LESSON_INDEX) Integer lessonIndex) throws Exception {
        HttpResContent<JSONArray> hrc = new HttpResContent<>("获取课堂互动知识点列表");
        // check.
        checkParam(PARAM_COURSE_ID, courseId);
        checkParam(PARAM_LESSON_INDEX, lessonIndex);
        List<String> retList = subjectQuestionService.listTag(courseId, lessonIndex);
        JSONArray retArr = new JSONArray();
        for (String s : retList) {
            JSONObject obj = new JSONObject();
            obj.put("content", s);
            retArr.add(obj);
        }
        hrc.printLogAndResponse(retArr);
    }

    @RequestMapping(value = "/get_point_gist.do", method = RequestMethod.POST)
    public void getPointGist(@RequestParam(PARAM_COURSE_ID) Integer courseId,
                             @RequestParam(PARAM_LESSON_INDEX) Integer lessonIndex) throws Exception {
        HttpResContent<String> hrc = new HttpResContent<>("获取知识点概要");
        // check.
        checkParam(PARAM_COURSE_ID, courseId);
        checkParam(PARAM_LESSON_INDEX, lessonIndex);
        String retStr = subjectQuestionService.getPointGist(courseId, lessonIndex);
        hrc.printLogAndResponse(retStr);
    }


    @RequestMapping(value = "/save_mould_list.do", method = RequestMethod.POST)
    public void saveMouldList(@RequestParam(PARAM_COURSE_ID) Integer courseId,
                              @RequestParam(PARAM_LESSON_INDEX) Integer lessonIndex,
                              @RequestParam(PARAM_DATA_STR) String dataStr) throws Exception {
        HttpResContent<Boolean> hrc = new HttpResContent<>("保存课堂互动模板列表");
        // check.
        checkParam(PARAM_COURSE_ID, courseId);
        checkParam(PARAM_LESSON_INDEX, lessonIndex);
        subjectQuestionService.saveMouldList(courseId, lessonIndex, JSON.parseArray(dataStr, String.class));
        hrc.printLogAndResponse(true);
    }

    @RequestMapping(value = "/save_tag_list.do", method = RequestMethod.POST)
    public void saveTagList(@RequestParam(PARAM_COURSE_ID) Integer courseId,
                            @RequestParam(PARAM_LESSON_INDEX) Integer lessonIndex,
                            @RequestParam(PARAM_DATA_STR) String dataStr) throws Exception {
        HttpResContent<Boolean> hrc = new HttpResContent<>("保存课堂互动知识点列表");
        // check.
        checkParam(PARAM_COURSE_ID, courseId);
        checkParam(PARAM_LESSON_INDEX, lessonIndex);
        subjectQuestionService.saveTagList(courseId, lessonIndex, JSON.parseArray(dataStr, String.class));
        hrc.printLogAndResponse(true);
    }

    @RequestMapping(value = "/save_point_gist.do", method = RequestMethod.POST)
    public void savePointGist(@RequestParam(PARAM_COURSE_ID) Integer courseId,
                              @RequestParam(PARAM_LESSON_INDEX) Integer lessonIndex,
                              @RequestParam(PARAM_DATA_STR) String dataStr) throws Exception {
        HttpResContent<Boolean> hrc = new HttpResContent<>("保存知识点概要");
        // check.
        checkParam(PARAM_COURSE_ID, courseId);
        checkParam(PARAM_LESSON_INDEX, lessonIndex);
        subjectQuestionService.savePointGist(courseId, lessonIndex, dataStr);
        hrc.printLogAndResponse(true);
    }

    @RequestMapping(value = "/save_classroom_test_record.do", method = RequestMethod.POST)
    public void saveClassroomTestRecord(@RequestParam(PARAM_EEO_CLASS_ID) Integer eeoClassId,
                                        @RequestParam(PARAM_SUBJECT_QUESTION_ID) Integer subjectQuestionId,
                                        @RequestParam(PARAM_TEST_NUM) Integer testNum,
                                        @RequestParam(PARAM_QUESTION_SIZE) Integer questionSize,
                                        @RequestParam(PARAM_DATA_STR) String dataStr) throws Exception {
        HttpResContent<Boolean> hrc = new HttpResContent<>("保存课堂互动记录");
        // check.
        checkParam(PARAM_EEO_CLASS_ID, eeoClassId);
        checkParam(PARAM_SUBJECT_QUESTION_ID, subjectQuestionId);
        checkParam(PARAM_DATA_STR, dataStr);
        checkParam(PARAM_TEST_NUM, testNum);
        homeworkRecordService.saveClassroomTestRecord(eeoClassId, subjectQuestionId, testNum, questionSize, dataStr);
        hrc.printLogAndResponse(true);
    }

}
